package oneplay.YonghongBITools;

import lombok.extern.slf4j.Slf4j;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class XMLDocument {
    private final XPathFactory xPathFactory = XPathFactory.instance();
    private final Document document;
    private final String content;

    public XMLDocument(String content) throws IOException, JDOMException {
        this.content = content;
        SAXBuilder builder = new SAXBuilder();
        builder.setExpandEntities(false);
        builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        document = builder.build(new StringReader(content));
    }

    public Document getDocument() {
        return document;
    }

    public String getContent() {
        return content;
    }

    /**
     * 根据 xpath 获取第一个结果内容
     *
     * @param xpath xpath表达式
     * @return xpath查询结果，找不到结果返回null
     */
    public String getFirstElementText(String xpath) {
        Element element = getFirstElement(xpath);
        return element == null ? null : element.getText();
    }

    /**
     * 根据 xpath 获取内容
     *
     * @param xpath xpath表达式
     * @return xpath查询结果
     */
    public List<String> getElementsValueText(String xpath) {
        return getElements(xpath).stream().map(Element::getText).collect(Collectors.toList());
    }

    /**
     * 根据 xpath 获取内容
     *
     * @param xpath xpath表达式
     * @return xpath查询结果
     */
    public Element getFirstElement(String xpath) {
        XPathExpression<Element> xPathExpression = xPathFactory.compile(xpath, Filters.element());
        return xPathExpression.evaluateFirst(document);
    }

    /**
     * 根据 xpath 获取内容
     *
     * @param xpath xpath表达式
     * @return xpath查询结果
     */
    public List<Element> getElements(String xpath) {
        XPathExpression<Element> xPathExpression = xPathFactory.compile(xpath, Filters.element());
        return xPathExpression.evaluate(document);
    }

    @Override
    public String toString() {
        return content;
    }

}
